<template>
  <div>
    <van-nav-bar title="城市列表" left-arrow @click-left="$router.back()" />
    <van-index-bar highlight-color="#21b97a" :index-list="letters">
      <van-index-anchor index="#">当前城市</van-index-anchor>
      <van-cell :title="cityNow" />
      <van-index-anchor index="热">热门城市</van-index-anchor>
      <van-cell
        v-for="(item, index) in hotcity"
        :key="index"
        :title="item.label"
        @click="chooseCity(item.label)"
      />
      <div v-for="(item) in indexList" :key="item.id">
        <van-index-anchor :index="item"></van-index-anchor>
        <van-cell v-for="(item,index) in getcellCity(item)" :key="index"  :title="item.label" @click="chooseCity(item.label)" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { getCityList, getHotCityList } from "@/api/search";
export default {
  data() {
    return {
      hotcity: [],
      allcity: [],
      letters:[],
      cityNow:'上海'
    };
  },
  created() {
    this.getAllCity(), 
    this.getHotCity();
    this.cityNow = localStorage.getItem('cityNow');
  },
  computed: {
    indexList() {
      let arr = this.allcity.map((item) => {
        return item.short.substring(0, 1).toUpperCase();
      });
      let arr1 = [...new Set(arr)];
      arr1.sort();
      this.letters = [...arr1]
      this.letters.unshift('#',"热")
      return arr1;
    },
  },
  methods: {
    async getAllCity() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration:1000
      });
      const res = await getCityList(1);
      console.log(res);
      this.allcity = res.body;
    },
    async getHotCity() {
      const res = await getHotCityList();
      console.log(res);
      this.hotcity = res.body;
    },
    getcellCity(name){
      return this.allcity.filter(item=>item.short.substring(0,1).toUpperCase()===name)
    },
    chooseCity(name){
      this.cityNow = name
      localStorage.setItem('cityNow',name)
    }
  },
};
</script>

<style>

.van-index-bar__index{
 display: inline-block;
  height: 20px;
  width: 20px;
  padding:0;
  margin:3px 10px;
  text-align: center;
  line-height: 20px;
}
.van-index-bar__index--active{
  color:#fff !important;
  font-weight: 700;
  background-color: #21b97a;
  border-radius: 10px;
}

</style>
